import React, { Component } from 'react'
import Taro from '@tarojs/taro'
import { View } from '@tarojs/components'
import { AtButton,  AtForm ,AtInput } from 'taro-ui'

import {api_phone_exist} from '../../../utils/api.jsx'
import {api_replace_password} from '../../../utils/api.jsx'
import {api_sms} from '../../../utils/api.jsx'

export default class ResetPwd extends Component {

  constructor(props){
    super(props);
    this.state = {
      phone:'', // 手机号
      newPwd:'',  // 新密码
      newRePwd:'',  // 再次新密码
      code:'',  //验证码
      count: 60,  //验证码计时
      code_text: '发送验证码',   // 按钮文本
      disableBtn: false, //‘发送验证码’按钮是否禁用
    }
  }

  toLogin = () => {
    Taro.reLaunch({url: '/pages/pagesB/login/login'})
  }

  countDown = () => {
    let count = this.state.count
    const timer = setInterval(() => {
      this.setState({
        count:(count--),
        disableBtn:true,
        code_text:count + 'S后重发'
      },() => {
        if(count == 0){
          clearInterval(timer)
          this.setState({
            disableBtn:false,
            count: 60,
            code_text:'发送验证码'
          })
        }
      })
    },1000)
  }

  // 用户点击发送验证码时检查手机号
  verifyPhoneExist = async () => {
    const params = {
      url: api_phone_exist,
      data: {
        phone:this.state.phone,
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success: (res) => {Taro.setStorageSync('isPhoneExist',res.data)},
      fail: (res) => {console.log(res.data)}
    }
    var myreg = /^[1][3,4,5,7,8,9][0-9]{9}$/
    if (!myreg.test(this.state.phone)) {
      // 手机号格式错误时，直接返回，不会发送数据
      if(this.state.phone.length == 0){
        Taro.showToast({
          title: '请输入手机号',
          icon: 'none',
          duration: 2000
        })
        return false
      }else{
        Taro.showToast({
          title: '手机号格式错误',
          icon: 'none',
          duration: 2000
        })
      }      
      return false
    }else{
      await Taro.request(params)
      const isPhoneExist = Taro.getStorageSync('isPhoneExist')
      if(!isPhoneExist){
        Taro.showModal({
          title: 'Tip',
          cancelText:'取消',
          confirmText:'确认',
          content: '您的手机号尚未注册!前往注册',
          success: function (res) {
            if (res.confirm) {
              Taro.navigateTo({url: '/pages/pagesB/bindPhone/bindPhone'})
            } else if (res.cancel) {
              
            }
          }
        })
      }else{
        const params_2 = {
          url: api_sms,
          data: {
            phone:this.state.phone,
            flag:1
          },
          method: 'POST',
          header: {
            'content-type': 'application/x-www-form-urlencoded' // 默认值
          },
          success: (res) => {Taro.setStorageSync('smsFlag',res.data)},
          fail: (res) => {console.log(res.data)}
        }
        await Taro.request(params_2)
        const smsFlag = Taro.getStorageSync('smsFlag')
        if(smsFlag){
          Taro.showToast({
            title: '验证码已发送',
            icon: 'none',
            duration: 2000
          })
          this.countDown()
        }
        return true
      }
    }
  }

  // 用户点击确定时再次验证
  request = async () => {
    // 询问手机号是否已注册
    const params_1 = {
      url: api_phone_exist,
      data: {
        phone:this.state.phone,
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success: (res) => {Taro.setStorageSync('isPhoneExist',res.data)
     },
      fail: (res) => {console.log(res.data)}
    }

    // 进行重置密码的数据请求
    const params_2 = {
      url: api_replace_password,
      data: {
        phone:this.state.phone,
        newPwd:this.state.newPwd,
        code:this.state.code
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success: (res) => {Taro.setStorageSync('isReset',res.data)
     },
      fail: (res) => {console.log(res.data)}
    }
    
    var myreg = /^[1][3,4,5,7,8,9][0-9]{9}$/;
    if (!myreg.test(this.state.phone)) {
      // 手机号格式错误时，直接返回，不会发送数据
      if(this.state.phone.length == 0){
        Taro.showToast({
          title: '请输入手机号',
          icon: 'none',
          duration: 2000
        })
      }else{
        Taro.showToast({
          title: '手机号格式错误',
          icon: 'none',
          duration: 2000
        })
      }      
      return
    } else if(this.state.code.length == 0){
      Taro.showToast({
        title: '请输入验证码',
        icon: 'none',
        duration: 2000
      })
    } else if(this.state.newPwd.length < 6){
      if(this.state.newPwd.length == 0){
        Taro.showToast({
          title: '请输入密码',
          icon: 'none',
          duration: 2000
        })
      }else{
        Taro.showToast({
          title: '密码长度必须不小于6',
          icon: 'none',
          duration: 2000
        })
      }
    } else if(this.state.newPwd != this.state.newRePwd){
      Taro.showToast({
        title: '两次输入密码必须一致',
        icon: 'none',
        duration: 2000
      })
    } else{
      // 输入正确后才会发送请求
      await Taro.request(params_1)
      const isPhoneExist = Taro.getStorageSync('isPhoneExist')
      if(!isPhoneExist){
        Taro.showModal({
          title: 'Tip',
          cancelText:'取消',
          confirmText:'确认',
          content: '您的手机号尚未注册!前往注册',
          success: function (res) {
            if (res.confirm) {
              Taro.navigateTo({url: '/pages/pagesB/bindPhone/bindPhone'})
            } else if (res.cancel) {
              
            }
          }
        })
      }else{
        await Taro.request(params_2)
        const isReplaceSuccess = Taro.getStorageSync('isReset')
        if(isReplaceSuccess){
          Taro.showToast({
            title: '重置密码成功',
            icon: 'success',
            duration: 1000
          })
          // 更改密码后需重新登录，把用户之前登录信息清空
          Taro.removeStorageSync('userInfo')
          setTimeout(this.toLogin,1000)
        }else{
          Taro.showToast({
            title: '重置密码失败',
            icon: 'none',
            duration: 2000
          })
        }
      }
    }
  }

  render () {
    return (
      <View>
        <AtForm>
          <AtInput className='phone'
            name='phone'
            border={false}
            title=''
            border='true'
            type='phone'
            required='true'
            placeholder='请输入手机号码'
            value={this.state.phone}
            onChange={(e) =>this.setState({phone:e})}
          >
          </AtInput>  
          <AtInput className='code'
            name='code'
            border={true}
            title=''
            type='number'
            placeholder='请输入验证码'
            value={this.state.code}
            onChange={(e) =>this.setState({code:e})}
          >
            <AtButton className='codeBtn' size='small' disabled={this.state.disableBtn} onClick={this.verifyPhoneExist}>{this.state.code_text}</AtButton>
          </AtInput>
          <AtInput className='newPwd'
            name='newPwd'
            title=''
            type='password'
            required='true'
            border='true'
            placeholder='请输入新密码'
            value={this.state.newPwd}
            onChange={(e) =>this.setState({newPwd:e})}
          >
          </AtInput>
          <AtInput className='newRePwd'
            name='newRePwd'
            title=''
            type='password'
            required='true'
            border='true'
            placeholder='确认新密码'
            value={this.state.newRePwd}
            onChange={(e) =>this.setState({newRePwd:e})}
          >
          </AtInput>
          <button className='verifyBtn' type='primary' onClick={this.request} style='width:95%;margin-top:10px;margin-left: 2.5%;margin-right: 2.5%'>确定</button>
        </AtForm>
      </View>
    )
  }
}